"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dayjs_1 = __importDefault(require("dayjs"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const child_process_1 = require("child_process");
const electron_1 = require("electron");
const ps_1 = require("ee-core/ps");
const log_1 = require("ee-core/log");
const config_1 = require("ee-core/config");
const framework_1 = require("../service/framework");
const sqlitedb_1 = require("../service/database/sqlitedb");
const auto_updater_1 = require("../service/os/auto_updater");
/**
 * framework - demo
 * @class
 */
class FrameworkController {
    /**
     * 所有方法接收两个参数
     * @param args 前端传的参数
     * @param event - ipc通信时才有值。详情见：控制器文档
     */
    /**
     * sqlite数据库操作
     */
    sqlitedbOperation(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { action, info, delete_name, update_name, update_age, search_age, data_dir } = args;
            const data = {
                action,
                result: null,
                all_list: [],
                code: 0
            };
            try {
                // test
                sqlitedb_1.sqlitedbService.getDataDir();
            }
            catch (err) {
                console.log(err);
                data.code = -1;
                return data;
            }
            switch (action) {
                case 'add':
                    data.result = yield sqlitedb_1.sqlitedbService.addTestDataSqlite(info);
                    ;
                    break;
                case 'del':
                    data.result = yield sqlitedb_1.sqlitedbService.delTestDataSqlite(delete_name);
                    ;
                    break;
                case 'update':
                    data.result = yield sqlitedb_1.sqlitedbService.updateTestDataSqlite(update_name, update_age);
                    break;
                case 'get':
                    data.result = yield sqlitedb_1.sqlitedbService.getTestDataSqlite(search_age);
                    break;
                case 'getDataDir':
                    data.result = yield sqlitedb_1.sqlitedbService.getDataDir();
                    break;
                case 'setDataDir':
                    data.result = yield sqlitedb_1.sqlitedbService.setCustomDataDir(data_dir || "");
                    break;
            }
            data.all_list = yield sqlitedb_1.sqlitedbService.getAllTestDataSqlite();
            return data;
        });
    }
    /**
     * 调用其它程序（exe、bash等可执行程序）
     *
     */
    openSoftware(args) {
        const { softName } = args;
        const softwarePath = path_1.default.join((0, ps_1.getExtraResourcesDir)(), softName);
        log_1.logger.info('[openSoftware] softwarePath:', softwarePath);
        // 检查程序是否存在
        if (!fs_1.default.existsSync(softwarePath)) {
            return false;
        }
        // 命令行字符串 并 执行, start 命令后面的路径要加双引号
        const cmdStr = `start "${softwarePath}"`;
        (0, child_process_1.exec)(cmdStr);
        // 方法二
        // 使用cross模块
        return true;
    }
    /**
     * 检测http服务是否开启
     */
    checkHttpServer() {
        return __awaiter(this, void 0, void 0, function* () {
            const httpConfig = (0, config_1.getConfig)().httpServer;
            if (!httpConfig || !('enable' in httpConfig) || !('protocol' in httpConfig) || !('host' in httpConfig) || !('port' in httpConfig)) {
                return { enable: false, server: '' };
            }
            const { enable, protocol, host, port } = httpConfig;
            const url = `${protocol}${host}:${port}`;
            console.log('[checkHttpServer] url:', url);
            const data = {
                enable: enable,
                server: url
            };
            return data;
        });
    }
    /**
     * 一个 http 请求
     * args 是 前端传的参数
     * ctx 是 koa 的 ctx 对象
     */
    doHttpRequest(args, ctx) {
        return __awaiter(this, void 0, void 0, function* () {
            const httpInfo = {
                args,
                method: ctx.request.method,
                query: ctx.request.query,
                body: ctx.request.body
            };
            log_1.logger.info('httpInfo:', httpInfo);
            const { id } = args;
            if (!id) {
                return false;
            }
            const dir = electron_1.app.getPath(id);
            electron_1.shell.openPath(dir);
            return true;
        });
    }
    /**
     * 一个socket io请求访问此方法
     */
    doSocketRequest(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { id } = args;
            if (!id) {
                return false;
            }
            const dir = electron_1.app.getPath(id);
            electron_1.shell.openPath(dir);
            return true;
        });
    }
    /**
     * 异步消息类型
     */
    ipcInvokeMsg(args) {
        return __awaiter(this, void 0, void 0, function* () {
            let timeNow = (0, dayjs_1.default)().format('YYYY-MM-DD HH:mm:ss');
            const data = args + ' - ' + timeNow;
            return data;
        });
    }
    /**
     * 同步消息类型
     */
    ipcSendSyncMsg(args) {
        return __awaiter(this, void 0, void 0, function* () {
            let timeNow = (0, dayjs_1.default)().format('YYYY-MM-DD HH:mm:ss');
            const data = args + ' - ' + timeNow;
            return data;
        });
    }
    /**
     * 双向异步通信
     */
    ipcSendMsg(args, event) {
        const { type, content } = args;
        const data = framework_1.frameworkService.bothWayMessage(type, content, event);
        return data;
    }
    /**
     * 任务
     */
    someJob(args, event) {
        const { jobId, action } = args;
        let result = null;
        switch (action) {
            case 'create':
                result = framework_1.frameworkService.doJob(jobId, action, event);
                break;
            case 'close':
                framework_1.frameworkService.doJob(jobId, action, event);
                break;
            case 'pause':
                framework_1.frameworkService.doJob(jobId, action, event);
                break;
            case 'resume':
                framework_1.frameworkService.doJob(jobId, action, event);
                break;
            default:
        }
        let data = {
            jobId,
            action,
            result
        };
        return data;
    }
    /**
     * 创建任务池
     */
    createPool(args, event) {
        return __awaiter(this, void 0, void 0, function* () {
            let num = args.number;
            framework_1.frameworkService.doCreatePool(num, event);
            // test monitor
            framework_1.frameworkService.monitorJob();
            return;
        });
    }
    /**
     * 通过进程池执行任务
     */
    someJobByPool(args, event) {
        const { jobId, action } = args;
        let result = null;
        switch (action) {
            case 'run':
                result = framework_1.frameworkService.doJobByPool(jobId, action, event);
                break;
            default:
        }
        let data = {
            jobId,
            action,
            result
        };
        return data;
    }
    /**
     * 检查是否有新版本
     */
    checkForUpdater() {
        auto_updater_1.autoUpdaterService.checkUpdate();
        return;
    }
    /**
     * 下载新版本
     */
    downloadApp() {
        auto_updater_1.autoUpdaterService.download();
        return;
    }
    /**
     * 测试接口
     */
    hello(args) {
        log_1.logger.info('hello ', args);
    }
}
FrameworkController.toString = () => '[class FrameworkController]';
exports.default = FrameworkController;
